package cn.anecansaitin.whimsy.mixin.common;

import cn.anecansaitin.whimsy.common.event.ModEventHooks;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.projectile.AbstractArrow;
import net.minecraft.world.entity.projectile.Projectile;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.EntityHitResult;
import net.neoforged.neoforge.entity.PartEntity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

@Mixin(AbstractArrow.class)
public abstract class AbstractArrowMixin extends Projectile {
    public AbstractArrowMixin(EntityType<? extends Projectile> pEntityType, Level pLevel) {
        super(pEntityType, pLevel);
    }

    @Inject(method = "onHitEntity", at = @At(value = "INVOKE_ASSIGN", target = "Lnet/minecraft/world/entity/Entity;hurt(Lnet/minecraft/world/damagesource/DamageSource;F)Z"))
    public void inject$onHitEntity(EntityHitResult result, CallbackInfo ci) {
        Entity entity = result.getEntity();

        if (entity instanceof LivingEntity living) {
            ModEventHooks.onArrowHitLivingEntity(living, whimsy$castToArrow(this));
        } else if (entity instanceof PartEntity<?> partEntity && partEntity.getParent() instanceof LivingEntity living) {
            ModEventHooks.onArrowHitLivingEntity(living, whimsy$castToArrow(this));
        }
    }

    @Unique
    private static AbstractArrow whimsy$castToArrow(Entity entity) {
        return (AbstractArrow)entity;
    }
}
